package at.fhhgb.mc.android.mfb_hgb.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.ActionBar;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import at.fhhgb.mc.android.mfb_hgb.R;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.DatePickerDialog;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.ProgressDialog;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.TimePickerDialog;
import at.fhhgb.mc.android.mfb_hgb.dal.SelectOffer;
import at.fhhgb.mc.android.mfb_hgb.model.Offer;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;

public class SearchFragment extends Fragment implements OnTouchListener, TaskCaller {

	private java.text.DateFormat dateFormat;
	private View view;
	private ProgressDialog pDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_search, null);

		// Set Date-EditText
		EditText date = (EditText) view.findViewById(R.id.editText_search_date);
		date.setOnTouchListener(this);

		dateFormat = DateFormat.getDateFormat(getActivity());
		date.setText(dateFormat.format(new Date()));

		// Set Time-EditText
		EditText time = (EditText) view.findViewById(R.id.editText_search_time);
		time.setOnTouchListener(this);

		Calendar c = Calendar.getInstance();
		time.setText(String.format("%02d", c.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", c.get(Calendar.MINUTE)));

		// RadioGroup From/To
		RadioGroup test = (RadioGroup) view.findViewById(R.id.radioGroup_search_fromto);
		test.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				EditText location = (EditText) view.findViewById(R.id.editText_search_location);
				TextView textFromTo = (TextView) view.findViewById(R.id.textView_search_fromto);

				switch (checkedId) {
				case R.id.radio_search_from:
					location.setHint(getString(R.string.start));
					textFromTo.setText(getString(R.string.to));
					break;

				case R.id.radio_search_to:
					location.setHint(getString(R.string.destination));
					textFromTo.setText(getString(R.string.from));
					break;
				}
			}
		});

		// Search-Button
		Button search = (Button) view.findViewById(R.id.button_search_search);
		search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (((EditText) view.findViewById(R.id.editText_search_location)).getText().toString().isEmpty()) {
					TextView errorText = (TextView) view.findViewById(R.id.textView_search_error);
					errorText.setVisibility(TextView.VISIBLE);
					errorText.setText(getString(R.string.data_required));
				} else {
					pDialog = new ProgressDialog(getActivity());
					pDialog.show();
					doSearch();
				}
			}
		});

		return view;
	}

	private void doSearch() {
		((TextView) view.findViewById(R.id.textView_search_error)).setVisibility(TextView.INVISIBLE);

		String type = "1";
		String filterLoc = "SearchSource";
		String location = ((EditText) view.findViewById(R.id.editText_search_location)).getText().toString();
		String[] timeValues = ((EditText) view.findViewById(R.id.editText_search_time)).getText().toString().split(":");

		// Save date in Calendar-Object
		Calendar fromCal = Calendar.getInstance();
		try {
			fromCal.setTime(dateFormat.parse(((EditText) view.findViewById(R.id.editText_search_date)).getText().toString()));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// Selected Date - 1 hour
		fromCal.set(fromCal.get(Calendar.YEAR), fromCal.get(Calendar.MONTH), fromCal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(timeValues[0]) - 1, Integer.valueOf(timeValues[1]));

		// Selected Date + 1 hour
		Calendar toCal = Calendar.getInstance();
		toCal.set(fromCal.get(Calendar.YEAR), fromCal.get(Calendar.MONTH), fromCal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(timeValues[0]) + 1, Integer.valueOf(timeValues[1]));

		// Format for SQL-Date
		SimpleDateFormat sqlDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		// Set RadioButton-Selection to SearchParameter
		if (((RadioButton) view.findViewById(R.id.radio_search_search)).isChecked()) {
			type = "2";
		}

		if (((RadioButton) view.findViewById(R.id.radio_search_to)).isChecked()) {
			filterLoc = "SearchDestination";
		}

		new SelectOffer(SearchFragment.this).execute(new BasicNameValuePair("Type", type), new BasicNameValuePair(filterLoc, location), new BasicNameValuePair("FromSearchDeparture", sqlDateFormatter.format(fromCal.getTime())), new BasicNameValuePair("ToSearchDeparture", sqlDateFormatter.format(toCal.getTime())));
	}

	/**
	 * Opens the DatePicker
	 * 
	 * @param view
	 *            EditText for Date (touched)
	 */
	private void openDatePicker(View view) {
		Bundle params = new Bundle();
		Calendar cal = Calendar.getInstance();

		try {
			cal.setTime(dateFormat.parse(((EditText) view).getText().toString()));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		params.putSerializable("defaultDate", cal);
		params.putInt("editTextKey", view.getId());

		DialogFragment newFragment = new DatePickerDialog();
		newFragment.setArguments(params);
		newFragment.show(getActivity().getFragmentManager(), "datePicker");
	}

	/**
	 * Opens TimePicker
	 * 
	 * @param view
	 *            EditText for Time (touched)
	 */
	private void openTimePicker(View view) {
		Bundle params = new Bundle();
		String[] timeValues = ((EditText) view).getText().toString().split(":");
		Calendar cal = Calendar.getInstance();

		cal.set(0, 0, 0, Integer.valueOf(timeValues[0]), Integer.valueOf(timeValues[1]), 0);

		params.putSerializable("defaultTime", cal);
		params.putInt("editTextKey", view.getId());

		DialogFragment newFragment = new TimePickerDialog();
		newFragment.setArguments(params);
		newFragment.show(getActivity().getFragmentManager(), "timePicker");
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
			switch (arg0.getId()) {
			case R.id.editText_search_date:
				openDatePicker(arg0);
				break;

			case R.id.editText_search_time:
				openTimePicker(arg0);
				break;
			}
		}

		return true;
	}

	@Override
	public void onBackgroundTaskCompleted(Object result) {
		List<Offer> searchResult = (List<Offer>) result;

		if (searchResult == null || searchResult.isEmpty()) {
			TextView errorText = (TextView) view.findViewById(R.id.textView_search_error);
			errorText.setVisibility(TextView.VISIBLE);
			errorText.setText(getString(R.string.no_searchresults));
		} else {
			FragmentManager fragmentManager = getActivity().getFragmentManager();
			FragmentTransaction ft = fragmentManager.beginTransaction();
			FragmentSearchResult f = new FragmentSearchResult();

			f.setOffers(searchResult);

			ft.replace(R.id.container, f);
			ft.addToBackStack(null);
			ft.commit();
		}

		pDialog.dismiss();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);

		// inflater.inflate(R.menu.s, menu);

		ActionBar actionBar = getActivity().getActionBar();

		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(getResources().getStringArray(R.array.nav_items)[1]);
	}
}
